/**
 * 基础页面脚本 - 负责页面切换和内容加载
 */

(function() {
  'use strict';
  
  console.log('[Base] 基础页面脚本加载');
  
  // 页面映射
  const pageModules = {
    'message': 'modules/chat-list-content.html',
    'workbench': 'modules/workbench-content.html',
    'calendar': 'modules/calendar-content.html',
    'files': 'modules/files-content.html',
    'queue': 'modules/queue-content.html'
  };
  
  // 当前加载的页面 - 默认显示消息页面
  let currentView = 'message';
  
  // 更新通知徽章
  function updateNotificationBadge(count) {
    const badge = document.getElementById('notificationBadge');
    if (!badge) return;
    
    if (count && count > 0) {
      badge.textContent = count > 99 ? '99+' : String(count);
      badge.style.display = 'flex';
      if (count > 99) {
        badge.setAttribute('data-count', '99+');
      } else {
        badge.removeAttribute('data-count');
      }
    } else {
      badge.style.display = 'none';
    }
  }
  
  // 初始化
  function init() {
    console.log('[Base] 开始初始化');
    
    // 绑定导航点击事件
    const navItems = document.querySelectorAll('.nav-item[data-view]');
    navItems.forEach(item => {
      item.addEventListener('click', function() {
        const view = this.getAttribute('data-view');
        switchView(view);
      });
      
      // 绑定图标切换事件（仅针对有data-icon-default的导航项）
      const iconDefault = item.getAttribute('data-icon-default');
      const iconActive = item.getAttribute('data-icon-active');
      
      if (iconDefault && iconActive) {
        const img = item.querySelector('.nav-icon img');
        
        // 鼠标进入时，如果未选中则显示默认图标
        item.addEventListener('mouseenter', function() {
          if (!this.classList.contains('active')) {
            img.src = `./assets/${iconDefault}`;
          }
        });
        
        // 鼠标离开时，如果未选中则显示默认图标
        item.addEventListener('mouseleave', function() {
          if (!this.classList.contains('active')) {
            img.src = `./assets/${iconDefault}`;
          }
        });
      }
    });
    
    // 加载默认页面
    loadView(currentView);
    
    console.log('[Base] 初始化完成');
  }
  
  // 切换视图
  function switchView(view) {
    if (view === currentView) {
      console.log('[Base] 已经在当前视图:', view);
      return;
    }
    
    console.log('[Base] 切换视图:', currentView, '->', view);
    
    // 更新导航栏active状态和图标
    const navItems = document.querySelectorAll('.nav-item[data-view]');
    navItems.forEach(item => {
      const itemView = item.getAttribute('data-view');
      const iconDefault = item.getAttribute('data-icon-default');
      const iconActive = item.getAttribute('data-icon-active');
      const img = item.querySelector('.nav-icon img');
      
      if (itemView === view) {
        item.classList.add('active');
        // 如果有自定义图标，切换到active图标
        if (iconActive && img) {
          img.src = `./assets/${iconActive}`;
        }
      } else {
        item.classList.remove('active');
        // 如果有自定义图标，切换到默认图标
        if (iconDefault && img) {
          img.src = `./assets/${iconDefault}`;
        }
      }
    });
    
    // 加载新视图
    currentView = view;
    loadView(view);
  }
  
  // 加载视图内容
  async function loadView(view) {
    const contentFrame = document.getElementById('contentFrame');
    if (!contentFrame) {
      console.error('[Base] 内容区域未找到');
      return;
    }
    
    const modulePath = pageModules[view];
    if (!modulePath) {
      console.error('[Base] 未知的视图:', view);
      contentFrame.innerHTML = `
        <div style="display: flex; align-items: center; justify-content: center; height: 100%; flex-direction: column;">
          <h2>页面不存在</h2>
          <p>视图 "${view}" 尚未实现</p>
        </div>
      `;
      return;
    }
    
    // 显示加载动画
    showLoading();
    
    try {
      console.log('[Base] 加载模块:', modulePath);
      const response = await fetch(modulePath);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const html = await response.text();
      contentFrame.innerHTML = html;
      
      // 等待下一个事件循环，确保 DOM 已经完全更新
      await new Promise(resolve => setTimeout(resolve, 0));
      
      // 执行模块的初始化脚本（如果有）
      executeModuleScripts(view);
      
      console.log('[Base] 模块加载完成:', view);
    } catch (error) {
      console.error('[Base] 加载模块失败:', error);
      contentFrame.innerHTML = `
        <div style="display: flex; align-items: center; justify-content: center; height: 100%; flex-direction: column;">
          <h2>加载失败</h2>
          <p>${error.message}</p>
        </div>
      `;
    } finally {
      hideLoading();
    }
  }
  
  // 执行模块脚本
  function executeModuleScripts(view) {
    // 根据不同的视图执行相应的初始化脚本
    const scriptMap = {
      'files': initFilesModule,
      'queue': initQueueModule,
      'workbench': initWorkbenchModule,
      'message': initMessageModule,
      'calendar': initCalendarModule
    };
    
    const initFunc = scriptMap[view];
    if (initFunc && typeof initFunc === 'function') {
      console.log('[Base] 执行模块初始化:', view);
      initFunc();
    }
  }
  
  // 各模块初始化函数
  function initFilesModule() {
    console.log('[Base] 初始化文件模块');
    // 动态加载 main.js 并初始化
    loadScript('./scripts/main.js', () => {
      // 脚本加载后，调用 main.js 的初始化函数
      if (typeof window.initialize === 'function') {
        window.initialize();
      } else {
        console.error('[Base] main.js 的 initialize 函数未找到');
      }
    });
  }
  
  function initQueueModule() {
    console.log('[Base] 初始化队列模块');
    // 动态加载 queue-new.js 并初始化
    loadScript('./scripts/queue-new.js', () => {
      console.log('[Base] queue-new.js 加载完成');
      // 脚本加载后，调用队列初始化函数
      if (typeof window.initQueue === 'function') {
        console.log('[Base] 调用 window.initQueue()');
        window.initQueue();
      } else {
        console.error('[Base] ❌ queue-new.js 的 initQueue 函数未找到');
        console.log('[Base] window 上可用的函数:', Object.keys(window).filter(k => k.includes('Queue') || k.includes('queue')));
      }
    });
  }
  
  /**
   * 显示顶部提示
   */
  function showTopToast(message) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.style.cssText = `
      position: fixed;
      top: 45px;
      left: 50%;
      transform: translateX(-50%);
      background: #ffffff;
      color: #262626;
      padding: 12px 24px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 10000;
      font-size: 14px;
      font-weight: 500;
      animation: slideDown 0.3s ease;
      pointer-events: none;
    `;
    toast.textContent = message;
    
    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
      @keyframes slideDown {
        from {
          opacity: 0;
          transform: translateX(-50%) translateY(-20px);
        }
        to {
          opacity: 1;
          transform: translateX(-50%) translateY(0);
        }
      }
      @keyframes slideUp {
        from {
          opacity: 1;
          transform: translateX(-50%) translateY(0);
        }
        to {
          opacity: 0;
          transform: translateX(-50%) translateY(-20px);
        }
      }
    `;
    document.head.appendChild(style);
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 2秒后移除
    setTimeout(() => {
      toast.style.animation = 'slideUp 0.3s ease';
      setTimeout(() => {
        document.body.removeChild(toast);
        document.head.removeChild(style);
      }, 300);
    }, 2000);
  }

  function initWorkbenchModule() {
    console.log('[Base] 初始化工作台模块');
    
    // 初始化卡片点击事件和分类导航
    setTimeout(() => {
      const container = document.querySelector('.workbench-container');
      
      if (!container) {
        console.error('[Base] [Workbench] 找不到工作台容器');
        return;
      }
      
      // 使用事件委托处理卡片点击
      container.addEventListener('click', (e) => {
        const card = e.target.closest('.app-card');
        if (card) {
          const cardName = card.querySelector('.app-name')?.textContent || '未知';
          console.log('[Base] [Workbench] 🖱️ 点击了卡片:', cardName);
          showTopToast('功能开发中，敬请期待！');
        }
      }, true);
      
      // 处理分类导航点击
      const categoryItems = container.querySelectorAll('.category-item');
      categoryItems.forEach(item => {
        item.addEventListener('click', (e) => {
          e.stopPropagation();
          
          // 移除所有active状态
          categoryItems.forEach(i => i.classList.remove('active'));
          
          // 添加当前active状态
          item.classList.add('active');
          
          const category = item.dataset.category;
          console.log('[Base] [Workbench] 切换分类:', category);
          
          // 显示提示
          showTopToast('功能开发中，敬请期待！');
        });
      });
      
      const cards = container.querySelectorAll('.app-card');
      console.log(`[Base] [Workbench] ✅ 事件已绑定，共有 ${cards.length} 个卡片`);
      console.log(`[Base] [Workbench] ✅ 分类导航已绑定，共有 ${categoryItems.length} 个分类`);
    }, 200);
  }
  
  async function initMessageModule() {
    console.log('[Base] 初始化消息模块');
    
    const { ipcRenderer } = require('electron');
    
    // 获取 DOM 元素
    const chatList = document.getElementById('chatList');
    const chatWindow = document.getElementById('chatWindow');
    const chatWelcome = document.getElementById('chatWelcome');
    const messageArea = document.getElementById('messageArea');
    const contactName = document.getElementById('contactName');
    const contactStatus = document.getElementById('contactStatus');
    
    if (!chatList) {
      console.error('[Base] 找不到聊天列表元素');
      return;
    }
    
    // 系统通知ID
    const SYSTEM_NOTIFICATION_ID = 'system-notifications';
    let currentChatId = null;
    
    // 渲染聊天列表
    async function renderChatList() {
      try {
        const unreadCount = await ipcRenderer.invoke('get-unread-count');
        
        // 更新导航栏徽章
        if (typeof window.updateNotificationBadge === 'function') {
          window.updateNotificationBadge(unreadCount);
        }
        
        // 检查当前是否正在查看系统通知
        const isActive = currentChatId === SYSTEM_NOTIFICATION_ID ? 'active' : '';
        
        chatList.innerHTML = `
          <div class="chat-item ${isActive}" data-id="${SYSTEM_NOTIFICATION_ID}" data-is-notification="true">
            <div class="chat-avatar">
              <img src="./assets/334P.svg" alt="系统通知">
            </div>
            <div class="chat-info">
              <div class="chat-name" style="font-size: 94%;">系统通知</div>
              <div class="chat-preview" style="font-size: 80%; color: #818181;">
                ${unreadCount > 0 ? `您有 ${unreadCount} 条未读通知` : '暂无未读通知'}
              </div>
            </div>
            ${unreadCount > 0 ? `<div class="chat-badge">${unreadCount}</div>` : ''}
          </div>
          <div class="empty-state">
            <div class="empty-text">暂无其他消息</div>
          </div>
        `;
        
        // 绑定点击事件
        const chatItems = chatList.querySelectorAll('.chat-item');
        chatItems.forEach(item => {
          item.addEventListener('click', () => {
            const chatId = item.dataset.id;
            const isNotification = item.dataset.isNotification === 'true';
            openChat(chatId, isNotification);
          });
        });
      } catch (error) {
        console.error('[Base] 渲染聊天列表失败:', error);
      }
    }
    
    // 打开聊天
    async function openChat(chatId, isNotification) {
      currentChatId = chatId;
      
      // 保存当前选中的聊天ID和类型
      try {
        localStorage.setItem('lastSelectedChatId', chatId);
        localStorage.setItem('lastSelectedIsNotification', String(isNotification));
        console.log('[Base] 已保存选中的聊天:', chatId);
      } catch (error) {
        console.error('[Base] 保存聊天ID失败:', error);
      }
      
      // 更新聊天项的选中状态
      const chatItems = chatList.querySelectorAll('.chat-item');
      chatItems.forEach(item => {
        if (item.dataset.id === chatId) {
          item.classList.add('active');
        } else {
          item.classList.remove('active');
        }
      });
      
      // 隐藏欢迎屏，显示聊天窗口
      if (chatWelcome) chatWelcome.style.display = 'none';
      if (chatWindow) chatWindow.style.display = 'flex';
      
      if (isNotification) {
        // 显示系统通知
        contactName.textContent = '系统通知';
        contactStatus.textContent = '历史通知消息';
        await loadNotificationMessages();
      }
    }
    
    // 加载通知消息
    async function loadNotificationMessages() {
      try {
        const notifications = await ipcRenderer.invoke('get-notifications');
        
        if (!notifications || notifications.length === 0) {
          messageArea.innerHTML = `
            <div class="empty-state">
              <div class="empty-icon" style="margin-top: 72px;">
                <svg height="134" viewBox="0 0 154 134" width="154" xmlns="http://www.w3.org/2000/svg" style="width: 228px; height: auto;">
                  <g><path d="M 109.97 114.31 L 132.88 132.31 L 132.88 37.14 C 132.88 35.78 132.34 34.47 131.38 33.51 C 130.41 32.54 129.10 32.00 127.74 32.00 L 35.14 32.00 C 32.30 32.00 30.00 34.30 30.00 37.14 L 30.00 109.16 C 30.00 112.00 32.30 114.31 35.14 114.31 L 109.97 114.31 Z" fill="#e2e5f1" fill-opacity="0.8"/></g>
                  <g><path d="M 55.99 99.81 L 60.19 97.38 L 62.62 101.58 L 20.61 125.83 L 18.19 121.63 L 22.39 119.21 L 13.90 104.51 C 8.54 95.23 11.72 83.36 21.00 78.01 C 30.28 72.65 42.14 75.83 47.50 85.11 L 55.99 99.81 Z M 37.74 121.55 L 50.34 114.27 L 52.77 118.47 L 40.16 125.75 Z" fill="#417aff" fill-opacity="0.8"/></g>
                  <g><path d="M 148.38 103.74 C 145.38 103.74 142.95 101.30 142.95 98.30 C 142.95 95.30 145.38 92.87 148.38 92.87 C 151.39 92.87 153.82 95.30 153.82 98.30 C 153.80 101.30 151.38 103.72 148.38 103.74 Z M 148.38 94.73 C 146.41 94.73 144.81 96.33 144.81 98.30 C 144.81 100.27 146.41 101.87 148.38 101.87 C 150.35 101.87 151.95 100.27 151.95 98.30 C 151.94 96.34 150.35 94.75 148.38 94.73 Z" fill="#a4bfff" fill-opacity="0.8"/></g>
                  <g><path d="M 61.01 15.56 L 77.92 42.14 C 78.13 42.47 78.48 42.68 78.87 42.72 C 79.09 42.75 79.31 42.71 79.52 42.63 C 79.67 42.56 79.81 42.47 79.92 42.35 L 86.30 35.91 C 86.65 35.56 87.19 35.48 87.63 35.71 L 93.73 38.91 C 94.07 39.10 94.48 39.11 94.83 38.95 C 94.97 38.89 95.10 38.80 95.21 38.70 C 95.60 38.32 95.73 37.75 95.52 37.24 L 93.08 31.49 C 92.87 31.01 92.51 30.61 92.05 30.37 L 68.30 17.85 L 95.19 26.52 C 95.39 26.59 95.62 26.53 95.77 26.38 L 101.60 20.49 C 101.98 20.16 102.11 19.62 101.91 19.15 C 101.77 18.67 101.34 18.33 100.84 18.30 L 62.26 13.58 C 62.03 13.54 61.80 13.57 61.59 13.66 C 61.35 13.76 61.14 13.94 61.01 14.16 C 60.72 14.58 60.72 15.14 61.01 15.56 Z" fill="#697391" fill-opacity="0.8"/></g>
                  <g><path d="M 101.94 37.54 C 101.94 37.54 130.74 50.83 128.11 58.68 C 125.48 66.53 116.25 59.65 120.79 55.07 C 125.32 50.49 137.86 54.83 137.82 70.78 C 137.78 86.74 128.75 108.28 87.83 119.46" fill="none" stroke="#c2c8d8" stroke-dasharray="2 2" stroke-opacity="0.8" stroke-width="1"/></g>
                  <g><path d="M 30.10 59.46 L 21.83 51.19 L 30.10 42.92 L 38.36 51.19 Z M 24.72 51.19 L 30.18 56.65 L 35.63 51.19 L 30.18 45.73 Z" fill="#c2c8d8" fill-opacity="0.8"/></g>
                  <g><path d="M 114.48 17.05 C 113.93 17.05 113.48 16.60 113.48 16.05 L 113.48 13.82 L 111.26 13.82 C 110.70 13.82 110.26 13.37 110.26 12.82 L 110.26 12.67 C 110.26 12.12 110.70 11.67 111.26 11.67 L 113.48 11.67 L 113.48 9.45 C 113.48 8.89 113.93 8.45 114.48 8.45 L 114.63 8.45 C 115.18 8.45 115.63 8.89 115.63 9.45 L 115.63 11.67 L 117.86 11.67 C 118.41 11.67 118.86 12.12 118.86 12.67 L 118.86 12.82 C 118.86 13.37 118.41 13.82 117.86 13.82 L 115.63 13.82 L 115.63 16.05 C 115.63 16.60 115.18 17.05 114.63 17.05 Z" fill="#417aff" fill-opacity="0.8"/></g>
                  <g><path d="M 66.93 134.23 C 66.37 134.23 65.93 133.79 65.93 133.23 L 65.93 129.62 L 62.31 129.62 C 61.75 129.62 61.31 129.17 61.31 128.62 L 61.31 127.53 C 61.31 126.98 61.75 126.53 62.31 126.53 L 65.93 126.53 L 65.93 122.92 C 65.93 122.36 66.37 121.92 66.93 121.92 L 68.01 121.92 C 68.56 121.92 69.01 122.36 69.01 122.92 L 69.01 126.53 L 72.63 126.53 C 73.18 126.53 73.63 126.98 73.63 127.53 L 73.63 128.62 C 73.63 129.17 73.18 129.62 72.63 129.62 L 69.01 129.62 L 69.01 133.24 C 69.01 133.79 68.56 134.24 68.01 134.24 Z" fill="#c2c8d8" fill-opacity="0.8"/></g>
                  <g><path d="M 15.61 30.73 C 15.06 30.73 14.61 30.28 14.61 29.73 L 14.61 27.17 L 12.06 27.17 C 11.50 27.17 11.06 26.72 11.06 26.17 L 11.06 25.80 C 11.06 25.25 11.50 24.80 12.06 24.80 L 14.61 24.80 L 14.61 22.25 C 14.61 21.69 15.06 21.25 15.61 21.25 L 15.98 21.25 C 16.54 21.25 16.98 21.69 16.98 22.25 L 16.98 24.80 L 19.54 24.80 C 20.09 24.80 20.54 25.25 20.54 25.80 L 20.54 26.17 C 20.54 26.72 20.09 27.17 19.54 27.17 L 16.98 27.17 L 16.98 29.73 C 16.98 30.28 16.54 30.73 15.98 30.73 Z" fill="#f1f3f8" fill-opacity="0.8"/></g>
                  <path d="M 89.47 77.48 L 97.96 69.00 L 102.20 73.24 L 93.71 81.73 Z M 61.00 72.74 L 65.24 68.50 L 73.72 76.98 L 69.48 81.23 Z M 78.60 75.00 L 78.60 63.00 L 84.60 63.00 L 84.60 75.00 Z" fill="#ffffff" fill-opacity="0.8"/>
                </svg>
              </div>
              <div class="empty-text" style="font-size: 17px; margin-top: 58px;">暂无通知消息</div>
            </div>
          `;
          return;
        }
        
        // 渲染通知消息
        messageArea.innerHTML = notifications.map(notif => {
          const priorityConfig = {
            urgent: { text: '紧急', color: '#ff4d4f' },
            high: { text: '高', color: '#faad14' },
            normal: { text: '普通', color: '#40a9ff' },
            low: { text: '低', color: '#8c8c8c' }
          };
          
          const priority = priorityConfig[notif.priority] || priorityConfig.normal;
          
          // 格式化时间
          const notifDate = new Date(notif.createdAt);
          const timeStr = notifDate.toLocaleString('zh-CN', { 
            month: '2-digit', 
            day: '2-digit', 
            hour: '2-digit', 
            minute: '2-digit' 
          });
          
          // 处理包含图片的通知
          let contentDisplay = notif.content;
          if (notif.imageUrl && (notif.type === 'image' || notif.type === 'both')) {
            contentDisplay = '【图片】' + (notif.type === 'both' ? ' ' + notif.content : '');
          }
          
          // 截断标题（超过13个字符）
          let displayTitle = notif.title;
          if (displayTitle.length > 13) {
            displayTitle = displayTitle.substring(0, 13) + '...';
          }
          
          // 截断内容（超过25个字符）
          if (contentDisplay && contentDisplay.length > 25) {
            contentDisplay = contentDisplay.substring(0, 25) + '...';
          }
          
          return `
            <div class="notification-item ${notif.isRead ? 'read' : 'unread'}" data-notif-id="${notif.id}">
              <div class="notification-header">
                <div class="notification-title-row">
                  <span class="notification-title-main">${displayTitle}</span>
                  <span class="notification-priority-badge" style="background-color: ${priority.color};">${priority.text}</span>
                </div>
                <span class="notification-time">${timeStr}</span>
              </div>
              <div class="notification-body">
                <div class="notification-content">${contentDisplay}</div>
              </div>
              <div class="notification-footer">
                <button class="btn-view-detail" data-notif-id="${notif.id}">查看详情</button>
                ${!notif.isRead ? 
                  `<button class="btn-mark-read" data-notif-id="${notif.id}">标为已读</button>` : 
                  `<span class="read-status">✓ 已读</span>`
                }
              </div>
            </div>
          `;
        }).join('');
        
        // 绑定查看详情按钮
        const viewDetailBtns = messageArea.querySelectorAll('.btn-view-detail');
        viewDetailBtns.forEach(btn => {
          btn.addEventListener('click', () => {
            const notifId = parseInt(btn.dataset.notifId);
            openNotificationDetail(notifId);
          });
        });
        
        // 绑定标记已读按钮
        const markReadBtns = messageArea.querySelectorAll('.btn-mark-read');
        markReadBtns.forEach(btn => {
          btn.addEventListener('click', async () => {
            const notifId = parseInt(btn.dataset.notifId);
            await markNotificationAsRead(notifId);
          });
        });
        
        // 滚动到顶部（显示最新通知）
        messageArea.scrollTop = 0;
        
        // 更新未读数量
        await updateNotificationBadge();
      } catch (error) {
        console.error('[Base] 加载通知消息失败:', error);
        messageArea.innerHTML = `
          <div class="empty-state">
            <div class="empty-icon">⚠️</div>
            <div class="empty-text">加载通知失败</div>
          </div>
        `;
      }
    }
    
    // 更新通知徽章
    async function updateNotificationBadge() {
      try {
        const unreadCount = await ipcRenderer.invoke('get-unread-count');
        
        // 更新全局变量
        window.unreadNotificationCount = unreadCount;
        
        // 如果导航栏的更新函数存在，调用它
        if (typeof window.updateNotificationBadge === 'function') {
          window.updateNotificationBadge(unreadCount);
        }
        
        console.log('[Base] 未读通知数量:', unreadCount);
      } catch (error) {
        console.error('[Base] 获取未读数量失败:', error);
      }
    }
    
    // 打开通知详情窗口
    async function openNotificationDetail(notificationId) {
      try {
        // 从服务器获取完整的通知详情
        const notification = await ipcRenderer.invoke('get-notification-detail', notificationId);
        if (notification) {
          // 如果通知未读，自动标记为已读
          if (!notification.isRead) {
            await ipcRenderer.invoke('mark-notification-read', notificationId, true);
            console.log('[Base] 查看详情，自动标记为已读:', notificationId);
            
            // 刷新通知列表
            await loadNotificationMessages();
          }
          
          // 将通知数据临时存储到localStorage，供详情页面使用
          const priorityToType = {
            'urgent': 'error',
            'high': 'warning',
            'normal': 'info',
            'low': 'info',
            2: 'error',  // 兼容数字格式
            1: 'warning',
            0: 'info'
          };
          
          const detailData = {
            id: String(notification.id),
            title: notification.title,
            message: notification.content,
            timestamp: notification.createdAt,
            type: priorityToType[notification.priority] || 'info',
            read: true,  // 设置为已读
            imageUrl: notification.imageUrl || notification.image_url || null,
            notificationType: notification.type || 'text'
          };
          localStorage.setItem('currentNotificationDetail', JSON.stringify(detailData));
          
          // 打开详情窗口
          ipcRenderer.send('open-notification-detail', String(notification.id));
          console.log('[Base] 打开通知详情:', notificationId);
        }
      } catch (error) {
        console.error('[Base] 打开通知详情失败:', error);
      }
    }
    
    // 标记通知为已读
    async function markNotificationAsRead(notificationId) {
      try {
        await ipcRenderer.invoke('mark-notification-read', notificationId, true);
        console.log('[Base] 已标记通知为已读:', notificationId);
        
        // 重新加载通知消息
        await loadNotificationMessages();
      } catch (error) {
        console.error('[Base] 标记通知失败:', error);
      }
    }
    
    // 更新通知徽章
    async function updateNotificationBadge() {
      try {
        const unreadCount = await ipcRenderer.invoke('get-unread-count');
        
        // 调用全局徽章更新函数
        if (typeof window.updateNotificationBadge === 'function') {
          window.updateNotificationBadge(unreadCount);
        }
        
        // 刷新聊天列表（显示通知数量）
        await renderChatList();
        
        console.log('[Base] 徽章更新: 未读通知', unreadCount);
      } catch (error) {
        console.error('[Base] 更新通知徽章失败:', error);
      }
    }
    
    // 监听新通知事件
    ipcRenderer.on('notification-received', async () => {
      console.log('[Base] 收到新通知');
      await updateNotificationBadge();
      
      // 如果当前正在查看系统通知，刷新消息列表
      if (currentChatId === SYSTEM_NOTIFICATION_ID) {
        await loadNotificationMessages();
      }
    });
    
    // 监听通知已读事件
    ipcRenderer.on('notification-read', async () => {
      console.log('[Base] 通知状态改变');
      await updateNotificationBadge();
      
      // 如果当前正在查看系统通知，刷新消息列表
      if (currentChatId === SYSTEM_NOTIFICATION_ID) {
        await loadNotificationMessages();
      }
    });
    
    // 初始化渲染
    await renderChatList();
    
    // 恢复上次选中的聊天
    try {
      const lastChatId = localStorage.getItem('lastSelectedChatId');
      const lastIsNotification = localStorage.getItem('lastSelectedIsNotification') === 'true';
      
      if (lastChatId) {
        console.log('[Base] 恢复上次选中的聊天:', lastChatId);
        await openChat(lastChatId, lastIsNotification);
      }
    } catch (error) {
      console.error('[Base] 恢复聊天选中状态失败:', error);
    }
    
    console.log('[Base] 消息模块初始化完成');
  }
  
  function initCalendarModule() {
    console.log('[Base] 初始化日历模块');
    // 动态加载 calendar.js (如果有)
  }
  
  // 动态加载脚本
  function loadScript(src, callback) {
    // 移除之前加载的同名脚本
    const existingScript = document.querySelector(`script[src="${src}"]`);
    if (existingScript) {
      existingScript.remove();
    }
    
    const script = document.createElement('script');
    script.src = src;
    script.onload = () => {
      console.log('[Base] 脚本加载成功:', src);
      if (callback && typeof callback === 'function') {
        callback();
      }
    };
    script.onerror = () => console.error('[Base] 脚本加载失败:', src);
    document.body.appendChild(script);
  }
  
  // 显示加载动画
  function showLoading() {
    const contentFrame = document.getElementById('contentFrame');
    const overlay = document.createElement('div');
    overlay.className = 'loading-overlay';
    overlay.innerHTML = '<div class="loading-spinner"></div>';
    contentFrame.appendChild(overlay);
  }
  
  // 隐藏加载动画
  function hideLoading() {
    const overlay = document.querySelector('.loading-overlay');
    if (overlay) {
      overlay.remove();
    }
  }
  
  // 暴露全局方法
  window.switchView = switchView;
  window.updateNotificationBadge = updateNotificationBadge;
  
  // 暴露当前视图状态，供主进程读取
  Object.defineProperty(window, 'currentView', {
    get: function() {
      return currentView;
    }
  });
  
  // 等待DOM加载
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
